package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.file.service.MinioService;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.wemedia.entity.WmMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 */
@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {


    @Autowired
    private MinioService minioService;
    /**
     * 上传
     * 上传到oss
     * 保存数据库
     * @param multipartFile
     * @return
     */
    @Override
    public String uploadPicture(MultipartFile multipartFile) {

        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId == null || userId==0){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //后缀
        String suffix = StringUtils.substringAfterLast(multipartFile.getOriginalFilename(), ".");
//        新的文件名
        String newFileName = UUID.randomUUID().toString() +suffix;
//        上传到minio
        try {
            String url = minioService.uploadImgFile("",newFileName,multipartFile.getInputStream());
//            保存数据库
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(url);
            wmMaterial.setUserId(userId);
            wmMaterial.setType(0);
            wmMaterial.setIsCollection(false);
            wmMaterial.setCreatedTime(new Date());
            boolean b = save(wmMaterial);
            if(!b){
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
            }
            return url;
        } catch (Exception e) {
            log.error("oss 上传失败！");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.UPLOAD_ERROR);
        }

    }
    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<WmMaterial> findByPage(WmMaterialDto dto) {
        //获取用户id
        Integer uid = UserThreadLocalUtils.getUserId();
//        设置查询条件
        QueryWrapper<WmMaterial> queryWrapper = new QueryWrapper<>();
        //按照当前用户查询
        queryWrapper.lambda().eq(WmMaterial::getUserId, uid);
        //是否是收藏
        if(dto.getIsCollection() != null && dto.getIsCollection()==1){
            queryWrapper.lambda().eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //按照日期倒序
        queryWrapper.lambda().orderByDesc(WmMaterial::getCreatedTime);
        //设置分页条件
        Page page = new Page(dto.getPage(), dto.getSize());
//        分页查询
        IPage<WmMaterial> materialIPage = this.page(page, queryWrapper);
        if(materialIPage == null || CollectionUtils.isEmpty(materialIPage.getRecords())){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        获取分页结果集合
        return new PageResult<>(dto.getPage(),
                dto.getSize(),
                materialIPage.getTotal(),
                materialIPage.getRecords());
    }
}